﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Runtime.InteropServices;
using UnityEngine.Networking;

public class WebCamController  {

    private static WebCamController _inst;
    public static WebCamController Inst
    {
        get
        {
            if (_inst == null)
            {
                _inst = new WebCamController();
            }
            return _inst;
        }
    }

    private const string POST_URL = "http://qa-k8s.fuxi.netease.com:31766/classifyUploadImage";
    //360-360 = 352-288   
    //720-720 = 720-720
    //如果这边的值太高的话，会出现卡顿的情况，目前自测720会卡顿，360不卡顿，最好能维持在刚好能识别的状态
    private int WebCamTextureWidth = 360;
    private int WebCamTextureHeight = 360;

    private WebCamTexture _webCamTexture;

    private Texture2D _currentTexture;
    private byte[] _currentTextureBytes;
    private bool _hasCamAuthorization;

    private int _videoRotationAngle;

    //这个是用于调安卓外部的函数
    AndroidJavaClass jc;

    //这下面的是用于调ios的函数
    [DllImport("__Internal")]
    private static extern void IOS_RequestCamAuthorization();

    [DllImport("__Internal")]
    private static extern bool IOS_CheckCamAuthorization();

    [DllImport("__Internal")]
    private static extern void IOS_JumpToSetPanel();



    private void Awake()
    {
        _webCamTexture = new WebCamTexture(WebCamTextureWidth, WebCamTextureHeight);
        _currentTexture = new Texture2D(WebCamTextureWidth, WebCamTextureHeight, TextureFormat.ARGB32, false);
#if UNITY_ANDROID && !UNITY_EDITOR
        jc = new AndroidJavaClass("com.netease.tools.WebCamera");
#endif
    }

    /// <summary>
    /// 这里要调用安卓的原生代码去动态的获取权限
    /// </summary>
    /// <returns></returns>
    public void RequestCamAuthorization()
    {
        //L12Debug.EditorLog("申请相机权限");
#if UNITY_ANDROID && !UNITY_EDITOR
        if(jc!=null){
        jc.CallStatic("RequestCamAuthorization");
        }
#else
        Application.RequestUserAuthorization(UserAuthorization.WebCam);
#endif

#if UNITY_IPHONE && !UNITY_EDITOR
        IOS_RequestCamAuthorization();
#endif
    }

    /// <summary>
    /// 检测相机权限是否获取到了
    /// </summary>
    /// <returns></returns>
    public bool CheckCamAuthorization()
    {
        bool isSuccess = false;
#if UNITY_ANDROID && !UNITY_EDITOR
        if(jc!=null){
        isSuccess = jc.CallStatic<bool>("CheckCamAuthorization");
        }
        else{
        isSuccess = true;
        }
        
#else
        isSuccess= Application.HasUserAuthorization(UserAuthorization.WebCam);
#endif

#if UNITY_IPHONE && !UNITY_EDITOR
        isSuccess = IOS_CheckCamAuthorization();
#endif
        _hasCamAuthorization = true;
        //L12Debug.EditorLog("申请到了相机权限");
        return isSuccess;
    }



    /// <summary>
    /// 这里是要用于跳转到手机设置面板的功能
    /// </summary>
    public void JumpToSetPanel()
    {
#if UNITY_ANDROID && !UNITY_EDITOR
        if(jc!=null){
        jc.CallStatic("JumpToSetPanel");
        }
#endif

#if UNITY_IPHONE && !UNITY_EDITOR
        IOS_JumpToSetPanel();
#endif
        //L12Debug.EditorLog("跳转至设置面板");
    }



    /// <summary>
    /// 先不管相机个数
    /// </summary>
    /// <returns></returns>
    public bool StartCamera(RawImage playerTrueFaceImage,int width,int height,bool isFrontFacing = true)
    {
        //L12Debug.EditorLog("直接尝试打开");
        if (CheckCamAuthorization())
        {
            //有权限的逻辑
            _webCamTexture = new WebCamTexture(width, height);
            if (WebCamTexture.devices.Length == 0)
            {
                //L12Debug.EditorLog("没有摄像头");
                return false;
            }

            if (isFrontFacing)
            {
                //调用前摄相头
                for (int i = 0; i < WebCamTexture.devices.Length; i++)
                {
                    //_webCamTexture.deviceName = WebCamTexture.devices[i].name;
                    if (WebCamTexture.devices[i].isFrontFacing)
                    {
                        _webCamTexture.deviceName = WebCamTexture.devices[i].name;
                        break;
                    }
                }
                            float scaleY = 1;
#if UNITY_ANDROID && !UNITY_EDITOR
        scaleY = _webCamTexture.videoVerticallyMirrored ? 1f : -1f; 
#endif

#if UNITY_IPHONE
        scaleY = _webCamTexture.videoVerticallyMirrored ? -1f : 1f; 
#endif
            //如果要镜像需要改变scaleY
            //float scaleY = _webCamTexture.videoVerticallyMirrored ? 1f : -1f; // Find if the camera is mirrored or not  
            playerTrueFaceImage.rectTransform.localScale = new Vector3(1f, scaleY, 1f); // Swap the mirrored camera 
            }
            else
            {
                //调用后摄相头
                for (int i = 0; i < WebCamTexture.devices.Length; i++)
                {
                    //_webCamTexture.deviceName = WebCamTexture.devices[i].name;
                    if (!WebCamTexture.devices[i].isFrontFacing)
                    {
                        _webCamTexture.deviceName = WebCamTexture.devices[i].name;
                        break;
                    }
                }
            }

            if (_webCamTexture.deviceName.Length <= 0 || _webCamTexture.deviceName == null)
            {
                return false;
            }

            //L12Debug.EditorLog("已经在拍了");
            playerTrueFaceImage.texture = _webCamTexture;
            _webCamTexture.Play();
            _videoRotationAngle = _webCamTexture.videoRotationAngle;
            //旋转角度
            playerTrueFaceImage.rectTransform.localEulerAngles = new Vector3(0, 0, -_videoRotationAngle);


            //playerTrueFaceImage.rectTransform.sizeDelta = new Vector2(_webCamTexture.width, _webCamTexture.height);
            _currentTexture = new Texture2D(WebCamTextureWidth, WebCamTextureHeight, TextureFormat.ARGB32, false);
            //L12Debug.EditorLog("W" + _webCamTexture.width);
            //L12Debug.EditorLog("H" + _webCamTexture.height);
            return true;
        }
        else
        {
            //没权限就显示  打开失败的图片,按钮等一大堆（还是放lua里吧）
            return false;
        }
    }

    /// <summary>
    /// 获取当前相机的截图
    /// </summary>
    public byte[] GetTexture()
    {
        if (CheckCamAuthorization() && WebCamTexture.devices.Length > 0 && _webCamTexture.deviceName.Length > 0)
        {
            //_currentTexture.SetPixels(_webCamTexture.GetPixels(0, 0, WebCamTextureWidth, WebCamTextureHeight));
            //根据这个值对相片数据进行旋转处理，如果不用处理也能识别最好,好像很卡的样子

            WebCamTextureWidth = _webCamTexture.width;
            WebCamTextureHeight = _webCamTexture.height;
            
            switch (_videoRotationAngle)
            {
                case 0:
                    _currentTexture.SetPixels(_webCamTexture.GetPixels(0, 0, WebCamTextureWidth, WebCamTextureHeight));
                    break;
                case 90:
                    for (int i = 0; i < WebCamTextureWidth; i++)
                    {
                        for (int j = 0; j < WebCamTextureHeight; j++)
                        {
                            _currentTexture.SetPixel(i, j, _webCamTexture.GetPixel(WebCamTextureHeight - 1 - j, i));
                        }
                    }
                    break;
                case 180:
                    for (int i = 0; i < WebCamTextureHeight; i++)
                    {
                        for (int j = 0; j < WebCamTextureWidth; j++)
                        {
                            _currentTexture.SetPixel(i, j, _webCamTexture.GetPixel(WebCamTextureHeight - 1 - i, WebCamTextureWidth - 1 - j));
                        }
                    }
                    break;
                case 270:
                    for (int i = 0; i < WebCamTextureWidth; i++)
                    {
                        for (int j = 0; j < WebCamTextureHeight; j++)
                        {
                            _currentTexture.SetPixel(i, j, _webCamTexture.GetPixel(j, WebCamTextureWidth - 1 - i));
                        }
                    }
                    break;

            }
            _currentTexture.Apply();
            _currentTextureBytes = _currentTexture.EncodeToPNG();
            if (_currentTextureBytes == null || _currentTextureBytes.Length <= 0)
            {
                //L12Debug.EditorLog("获取截图数据失败");
                return null;
            }
            return _currentTextureBytes;
        }
        else
        {
            //L12Debug.EditorLog("没权限或者没相机");
            return null;
        }
    }

    public void CloseCamera()
    {
        _webCamTexture.Stop();
    }

    /// <summary>
    /// 发数据
    /// </summary>
    /// <param name="data"></param>
    public IEnumerator SendTextureData(byte[] data)
    {
        WWWForm form = new WWWForm();
        form.AddBinaryData("image", data, "CurrentExpress.png", "image/png");
        UnityWebRequest request = UnityWebRequest.Post(POST_URL, form);
        request.uploadHandler.contentType = "image/png";

        //L12Debug.EditorLog("我开始传了");
        yield return request.SendWebRequest();
        //L12Debug.EditorLog(request.responseCode);
        if (request.isNetworkError)
        {

        }
        else
        {
            // Show results as text  200==OK
            if (request.responseCode == 200)
            {
            }
        }        
    }

}
